package cn.swu.ws;

import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MainServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StringBuilder stringBuilder= new StringBuilder();
        stringBuilder.append("<html><head><title>图书信息</title></head><body>");
        try(Connection connection = DBTool.getConnection()){
            try(Statement statement = connection.createStatement()){
                String sql="select * from book";
                try(ResultSet resultSet = statement.executeQuery(sql)){
                    while (resultSet.next()){
                        int id= resultSet.getInt("id");
                        String name= resultSet.getString("name");
                        String author = resultSet.getString("author");
                        float price = resultSet.getFloat("price");
                        String content = resultSet.getString("content");
                        System.out.println(id+" "+name+" "+author+" "+price+" "+content);
                        stringBuilder.append("<tr><td>").append(id).append("</td><td>").append(name).append("</td><td>").append(author).append("</td><td>").append(price).append("</td><td>").append(content).append("</td></tr>");
                    }
                }
            }
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        stringBuilder.append("</body></html>");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(stringBuilder.toString());
    }
}
